package com.aqie.easy.hash;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 438  s 中所有是 p 的字母异位词的子串，返回这些子串的起始索引,
 *      字母异位词指字母相同，但排列不同的字符串
 */
public class FindAnagrams {
    /**
     * 模板解法
     * @param s
     * @param p
     * @return
     */
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> res = new ArrayList<>();
        int left = 0, right = 0;
        HashMap<Character, Integer> needs = new HashMap<>();
        HashMap<Character, Integer> window = new HashMap<>();
        for (char c : p.toCharArray()){
            needs.put(c, needs.getOrDefault(c, 0) + 1);
        }
        int match = 0;
        while(right < s.length()){
            char c1 = s.charAt(right);
            if (needs.containsKey(c1)){
                window.put(c1, window.getOrDefault(c1, 0) + 1);
                if (window.get(c1).equals(needs.get(c1))){
                    match++;
                }
            }
            right++;

            while (match == needs.size()){
                if (right - left == p.length()){
                    res.add(left);
                }
                char c2 = s.charAt(left);
                if (needs.containsKey(c2)){
                    window.put(c2, window.get(c2) - 1);
                    if (window.get(c2) < needs.get(c2)){
                        match--;
                    }
                }
                left++;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        String s = "cbaebabacd";
        String p = "abc";
        s = "abab";
        p = "ab";
    }
}
